<template>
  <el-form ref="form" label-position="right" :model="form" :rules="rulesUnit" label-suffix="：" label-width="120px">

    <el-form-item label="手机号" prop="phone">
      <el-input v-model="form.phone" placeholder="输入手机号" :maxlength="11"></el-input>
    </el-form-item>
    <el-form-item label="验证码" prop="validCode">
      <div class="form_compact">
        <el-input v-model="form.validCode" placeholder="输入验证码" :maxlength="6"></el-input>
        <el-button type="primary" :disabled="verificationCodeText !== '获取验证码'" @click="queryVerificationCode">
          {{verificationCodeText}}
        </el-button>
      </div>
    </el-form-item>
    <el-form-item label="登录密码" prop="password">
      <el-input v-model="form.password" placeholder="输入登录密码" type="password" :maxlength="50"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="repeat">
      <el-input v-model="form.repeat" placeholder="输入确认密码" type="password" :maxlength="50"></el-input>
    </el-form-item>
  </el-form>
</template>

<script>
import { CHECK_PHONE, CHECK_ACCOUNT, CHECK_PASSWORD, CHECK_REPEAT} from './validator'
import {sendCode} from '@/services/model/common'
export default {
  props: ['value'],
  data() {
    return {
      // 单位类型
      EnumUnitTypeList: [],
      // 单位信息表单 校验规则
      rulesUnit: {
        phone: {required: true, validator: CHECK_PHONE},
        validCode: {required: true, message: '请输入验证码'},
        // email: {validator: CHECK_EMAIL},
        password: {required: true, validator: CHECK_PASSWORD},
        repeat: {required: true, validator: CHECK_REPEAT.bind(this)}
      },
      // 获取验证码文案
      verificationCodeText: '获取验证码'
    }
  },
  computed: {
    form: {
      get() {
        return this.value
      },
      set(value) {
        this.$emit('input', value)
      }
    }
  },
  methods: {
    // 获取验证码
    queryVerificationCode() {
      this.$refs.form.validateField('phone', async valid => {
        // valid为返回的错误message 正确时值为空
        if (!valid) {
          this.verificationCodeText = 60
          await sendCode({phone: this.form.phone})
          // 倒计时
          let timer = () => {
            setTimeout(() => {
              this.verificationCodeText--
              if (this.verificationCodeText > 0) timer()
              else this.verificationCodeText = '获取验证码'
            }, 1000)
          }
          timer()
        }
      })
    },
    // 内部表单校验
    _validatorForm() {
      return new Promise((resolve) => {
        this.$refs.form.validate((valid) => {
          valid && resolve()
        })
      })
    }
  },
}
</script>

<style lang="less" scoped>
  .form_compact {
    display: flex;

    & /deep/ .el-input input {
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
    }

    & /deep/ .el-button {
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
  }
  .el-button {
    padding-right: 40px;
  }
</style>
